package org.smi;

import java.io.File;

/**
 * <p>
 *
 * </p>
 *
 * @author ysm
 * @since 2024-08-10
 */
public class Rename {

    private static final String PREFIX = "prefix";
    private static final String SUFFIX = ".ts";

    private static final Integer plusNumber = 207;
    private static final String originalFilePath = "/Users/beyondsoft/Movies/Rui-03";

    public static void main(String[] args) throws Exception {
        Rename rename = new Rename();
        rename.getAllFiles(originalFilePath);

    }

    public void getAllFiles(String path) throws Exception {
        File originDir = new File(path);
        if (originDir.isFile()) {
            throw new Exception("请输入目录");
        }
        File[] files = originDir.getAbsoluteFile().listFiles();
        assert files != null;
        System.out.println("filesLength: " + files.length);
        for (File file : files) {
            System.out.println("---");
            String newFilePath = convertNewFileName(file.getAbsolutePath(), plusNumber + 1);
            this.renameFile(file.getAbsolutePath(), newFilePath);
        }

    }

    public String convertNewFileName(String fileName, Integer plusNumber) {
        String[] pathArr = fileName.split("/");
        String realName = pathArr[pathArr.length - 1];
        String dirName = pathArr[pathArr.length - 2];
        String otherName = fileName.replace(dirName + "/" + realName, "");
        String number = realName.replace(PREFIX, "").replace(SUFFIX, "");
        Integer numberInt = Integer.parseInt(number);
        numberInt += plusNumber;

        String convertNumber = "";
        if (numberInt < 10) {
            convertNumber = "000" + numberInt;
        } else if (numberInt < 100) {
            convertNumber = "00" + numberInt;
        } else if (numberInt < 1000) {
            convertNumber = "0" + numberInt;
        }
        fileName = PREFIX + convertNumber + SUFFIX;
        String newDir = otherName + dirName  + "-converted";
        File newFile = new File(newDir);
        if (!newFile.exists()) {
            newFile.mkdir();
        }

        return newFile + "/" + fileName;
    }

    public void renameFile(String originalFileName, String newFileName) {
        // 创建File对象，表示原始文件
        File originalFile = new File(originalFileName);

        // 创建File对象，表示目标文件
        File newFile = new File(newFileName);

        // 使用renameTo方法重命名文件
        boolean isSuccess = originalFile.renameTo(newFile);

        if (isSuccess) {
            System.out.println("文件重命名成功！");
        } else {
            System.out.println("文件重命名失败！");
        }
    }
}
